package org.toonWatch
import grails.converters.JSON
import com.metasieve.shoppingcart.ShoppingItem
import org.springframework.transaction.TransactionStatus

class ItemController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: 'showSearch')
    }
    
    def scaffold = true
    
    def String wrapSearchParm(value) {
		 '%'+value+'%'
    }
         
    def showSearch = {
        render (view:'searchAjax')
    }
    
    def displayItem = {
        def item = Item.findById(params.id)
        return [item : item, categoryItems: item.category.items]
    }
    
    def search= {
        def list
        if (params.description && params.name)
        list = Item.findAllByNameIlikeAndDescriptionIlike(wrapSearchParm(params.name), wrapSearchParm(params.description))
        else if (params.description)
        list = Item.findAllByDescriptionIlike(wrapSearchParm(params.description))
        else if (params.name)
        list = Item.findAllByNameIlike(wrapSearchParm(params.name))
			
        render(template:'searchResults', model:[searchresults:list])
    }
    
    def searchAjax = { }
    
    def simpleSearch= {
        def list
        if (params.name)
        list = Item.findAllByNameIlike(wrapSearchParm(params.name))

        chain(action:"searchAjax", model:[searchresults:list])
    }
    
    
    def renderProductPhoto = {
        def product = Item.findById(params.id)
        
        if (product?.image) {
            response.setContentLength(product.image.length)
            response.outputStream.write(product.image)
        } else {
            response.sendError(404)
        }
    }
    
    def itemDataAsJSON = {
        def list = []
        
        //take searchresult form _searchresult and tokenize into String Array
        def result = params.searchresults
        result = result.substring(1, result.length()-1)
        def allItemString = result.tokenize(',\n')
        allItemString = allItemString.collect{it.trim()}
     
        //search for items that match searchresult array and sort it according to params
        def allItems = Item.findAllByNameInList(allItemString, params)

        response.setHeader("Cache-Control", "no-store")
        allItems.each {
            //add to JSON result
            list << [
                id:it.id,
                image: '<a href="/item/displayItem/'+it.id+'">'+ '<img src="' + g.createLink(action: 'renderProductPhoto', id:it.id) + '" style="width:100px">' + '</a>',
                name: '<a href="/item/displayItem/'+it.id+'">' + it.name + '</a>',       
                category:it.category.toString(),
                price: it.price,
                brand: it.brand,
                description: it.description
            ]
        }
        def data = [
            totalRecords: allItemString.size(),
            results: list
        ]
        render data as JSON
    }


    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [itemInstanceList: Item.list(params), itemInstanceTotal: Item.count()]
    }

    def create = {
        def itemInstance = new Item()
        itemInstance.properties = params
        return [itemInstance: itemInstance]
    }

    def save = {
        
        Item.withTransaction {TransactionStatus status->
        
            def itemInstance = new Item(params)
            if (itemInstance.save(flush: true)) {
                itemInstance.shoppingItem = new ShoppingItem().save()
                
                println "item ID"
                println itemInstance.id
                
                println "SCID"
                println itemInstance.shoppingItem.id
                
                if(itemInstance.id != itemInstance.shoppingItem.id)
                status.setRollbackOnly()
                
                else itemInstance.save(flush: true)
                
                flash.message = "${message(code: 'default.created.message', args: [message(code: 'item.label', default: 'Item'), itemInstance.id])}"
                redirect(action: "show", id: itemInstance.id)
            }
            else {
                status.setRollbackOnly()
                render(view: "create", model: [itemInstance: itemInstance])
            }
        }
    }

    def show = {
        def itemInstance = Item.get(params.id)
        if (!itemInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'item.label', default: 'Item'), params.id])}"
            redirect(action: "list")
        }
        else {
            [itemInstance: itemInstance]
        }
    }

    def edit = {
        def itemInstance = Item.get(params.id)
        if (!itemInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'item.label', default: 'Item'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [itemInstance: itemInstance]
        }
    }

    def update = {
        def itemInstance = Item.get(params.id)
        if (itemInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (itemInstance.version > version) {
                    
                    itemInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'item.label', default: 'Item')] as Object[], "Another user has updated this Item while you were editing")
                    render(view: "edit", model: [itemInstance: itemInstance])
                    return
                }
            }
            itemInstance.properties = params
            if (!itemInstance.hasErrors() && itemInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'item.label', default: 'Item'), itemInstance.id])}"
                redirect(action: "show", id: itemInstance.id)
            }
            else {
                render(view: "edit", model: [itemInstance: itemInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'item.label', default: 'Item'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def itemInstance = Item.get(params.id)
        if (itemInstance) {
            try {
                itemInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'item.label', default: 'Item'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'item.label', default: 'Item'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'item.label', default: 'Item'), params.id])}"
            redirect(action: "list")
        }
    }
}
